'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  const { user_id } = event;
  try {
    const pkCollection = db.collection('pk_records');
    const pkRes = await pkCollection
      .where({ opponent_id: user_id, status: 'pending' })
      .limit(1)
      .get();
    if (!pkRes.data.length) {
      return { code: 0, data: {}, msg: '无待处理PK' };
    }
    const pk = pkRes.data[0];
    const challenger = (await db.collection('users').where({ _id: pk.challenger_id }).get()).data[0];
    return {
      code: 0,
      data: { pk_id: pk._id, challenger_name: challenger.name },
      msg: '找到待处理PK'
    };
  } catch (e) {
    console.error('检查PK失败:', e);
    return { code: -1, msg: `检查PK失败: ${e.message || '未知错误'}` };
  }
};